package com.xbongbong.coolapp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.businesstage.pojo.dto.StageGetDTO;
import com.xbongbong.coolapp.service.CoolAppHomeService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.coolapp.pojo.dto.CoolAppHomeMenuDTO;
import com.xbongbong.pro.coolapp.pojo.vo.CoolAppHomeMenuVO;
import com.xbongbong.pro.enums.AccessLinkEnum;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.menu.enums.CRMMenuEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.menu.pojo.vo.AppMenuListVO;
import com.xbongbong.pro.statistic.pojo.vo.CustomerInfoVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.CustomerFocusEntity;
import com.xbongbong.saas.domain.entity.CustomerStageLogEntity;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.model.CustomerFocusModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.CustomerStageLogModel;
import com.xbongbong.sys.model.CompanyConfigModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author zhushuainan
 * @title: CoolAppHomeServiceImpl
 * @projectName xbb-pro
 * @description: TODO
 * @date 2022/6/9 17:03
 */
@Service("coolAppHomeServiceImpl")
public class CoolAppHomeServiceImpl implements CoolAppHomeService {

    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private CustomerFocusModel customerFocusModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private CustomerStageLogModel customerStageLogModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private PaasFormModel paasFormModel;

    @Override
    public CoolAppHomeMenuVO getIndex(CoolAppHomeMenuDTO coolAppHomeMenuDTO) throws XbbException {
        CoolAppHomeMenuVO coolAppHomeMenuVO = new CoolAppHomeMenuVO();
        List<AppMenuListVO> commonFormList = new ArrayList<>();
        String corpid = coolAppHomeMenuDTO.getCorpid();
        String userId = coolAppHomeMenuDTO.getUserId();
        // 客户、跟进记录、合同
        List<String> asList = getBusinessAlias();
        Set<String> permSet = coolAppHomeMenuDTO.getLoginUser().getPermSet();
        //常用表单
        for (String alias : asList) {
            // 非客户、机会表单权限判断
            if (!Objects.equals(alias,XbbRefTypeEnum.CUSTOMER.getAlias()) && !Objects.equals(alias,XbbRefTypeEnum.ALL_OPPORTUNITY.getAlias()) &&!permSet.contains(alias)) {
                continue;
            }
            // 全部客户表单权限判断特殊处理(permSet里客户alis为customerManagement)
            if(Objects.equals(alias,XbbRefTypeEnum.CUSTOMER.getAlias()) && !permSet.contains(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getAlias())){
                continue;
            }
            // 全部机会表单权限判断特殊处理(permSet里客户alis为salesOpportunity)
            if(Objects.equals(alias,XbbRefTypeEnum.ALL_OPPORTUNITY.getAlias()) && !permSet.contains(XbbRefTypeEnum.SALES_OPPORTUNITY.getAlias())){
                continue;
            }
            PaasMenuEntity paasMenuEntity = paasMenuModel.getByAlias4Distributor(alias, corpid, DistributorMarkEnum.OTHER.getCode());
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByAlias(paasMenuEntity.getAlias());
            String url = paasMenuEntity.getUrl();
            String mobileUrl = paasMenuEntity.getMobileUrl();
            if (CRMMenuEnum.COMMUNICATE_PLAN.getAlias().equals(paasMenuEntity.getAlias())) {
                mobileUrl = AccessLinkEnum.COMMUNICATE_PLAN.getMobileUrl();
            }
            AppMenuListVO appMenuListVO = new AppMenuListVO();
            BeanUtil.copyProperties(paasMenuEntity, appMenuListVO);
            if (StringUtil.isNotEmpty(url)) {
                String stringBuilder = url +
                        "?subBusinessType=" + xbbRefTypeEnum.getCode() +
                        "&appId=" + appMenuListVO.getAppId() +
                        "&menuId=" + appMenuListVO.getId() +
                        "&saasMark=" + appMenuListVO.getSaasMark() +
                        "&distributorMark=" + appMenuListVO.getDistributorMark();
                appMenuListVO.setUrl(stringBuilder);
            }
            if (StringUtil.isNotEmpty(mobileUrl) && !Objects.equals(alias, XbbRefTypeEnum.SIGNIN.getAlias())) {
                StringBuilder stringBuilder = new StringBuilder(mobileUrl)
                        .append("?subBusinessType=").append(xbbRefTypeEnum.getCode())
                        .append("&appId=").append(appMenuListVO.getAppId())
                        .append("&name=").append(appMenuListVO.getName())
                        .append("&saasMark=").append(appMenuListVO.getSaasMark())
                        .append("&distributorMark=").append(appMenuListVO.getDistributorMark());
                if (Objects.equals(XbbRefTypeEnum.COMMUNICATE_PLAN.getAlias(), alias)) {
                    // 访客计划模块
                    stringBuilder.append("&businessType=").append(XbbRefTypeEnum.COMMUNICATE_PLAN.getCode());
                    stringBuilder.append("&menuId=").append(appMenuListVO.getId());
                    PaasFormEntity paasFormEntity = paasFormModel.getByMenuIdAndBusinessType(paasMenuEntity.getId().intValue(), coolAppHomeMenuDTO.getCorpid(), XbbRefTypeEnum.COMMUNICATE_PLAN.getCode());
                    if (null != paasFormEntity){
                        stringBuilder.append("&formId=").append(paasFormEntity.getId());
                    }
                }
                if (Objects.equals(XbbRefTypeEnum.WORK_REPORT.getAlias(), alias)){
                    stringBuilder.append("&menuId=").append(appMenuListVO.getId());
                }
//                if (Objects.equals(alias, XbbRefTypeEnum.CUSTOMER.getAlias()) || Objects.equals(alias, XbbRefTypeEnum.CUSTOMER_FOCUS.getAlias())
//                        || Objects.equals(alias, XbbRefTypeEnum.CUSTOMER_DEAL.getAlias()) || Objects.equals(alias, XbbRefTypeEnum.CUSTOMER_FOLLOW.getAlias())
//                        || Objects.equals(alias, XbbRefTypeEnum.CUSTOMER_PUBLIC.getAlias()) || Objects.equals(alias, XbbRefTypeEnum.CUSTOMER_RECYCLE.getAlias())
//                        || Objects.equals(alias, XbbRefTypeEnum.CUSTOMER_NEARBY.getAlias()) || Objects.equals(alias, XbbRefTypeEnum.ALL_OPPORTUNITY.getAlias())
//                        || Objects.equals(alias, XbbRefTypeEnum.KEY_OPPORTUNITY.getAlias()) || Objects.equals(alias, XbbRefTypeEnum.ALL_CLUE.getAlias())
//                        || Objects.equals(alias, XbbRefTypeEnum.CLUE_PUBLIC.getAlias()) || Objects.equals(alias, XbbRefTypeEnum.CLUE_RECYCLE.getAlias())) {
//                    stringBuilder.append("&menuId=").append(appMenuListVO.getParentId());
//                }
                appMenuListVO.setMobileUrl(stringBuilder.toString());
            }
            if (Objects.equals(alias, XbbRefTypeEnum.SIGNIN.getAlias())){
                String stringBuilder = "/signIn/select" +
                        "?appId=" + appMenuListVO.getAppId() +
                        "&menuId=" + appMenuListVO.getId() +
                        "&timestamp=" + DateTimeUtil.getLong();
                appMenuListVO.setMobileUrl(stringBuilder);
            }
            commonFormList.add(appMenuListVO);
        }
        //图表中心
        if (permSet.contains(ProPermissionAliasEnum.CHART_VIEW.getAlias())) {
            AppMenuListVO appMenuListVO = new AppMenuListVO();
            appMenuListVO.setAlias("chart");
            appMenuListVO.setIcon("header-icon app-icon-tubiaozhongxin");
            appMenuListVO.setName(I18nMessageUtil.getMessage(I18nStringConstant.CHART_CENTER));
            appMenuListVO.setMobileUrl("/chart-center/index");
            commonFormList.add(appMenuListVO);
        }
        coolAppHomeMenuVO.setCommonFormList(commonFormList);
        //审批
        int processPerm = permSet.contains(ProPermissionAliasEnum.PROCESS_VIEW.getAlias()) ? BasicConstant.ONE : BasicConstant.ZERO;
        coolAppHomeMenuVO.setProcessPerm(processPerm);
        boolean workFlowUpdate = commonHelp.isOpenWorkFlow(corpid);
        coolAppHomeMenuVO.setWorkFlowUpdate(workFlowUpdate);
        //阶段推进器
        boolean isShare;
        try {
            isShare = companyConfigModel.hasBeenEnable(corpid, CompanyConfigEnum.SHARE_FOCUS_CUSTOEMR.getAlias(), BasicConstant.IS_USE.toString());
        } catch (XbbException e) {
            isShare = Objects.equals(CompanyConfigEnum.SHARE_FOCUS_CUSTOEMR.getValue(), BasicConstant.IS_USE.toString());
        }
        //重点客户数据id
        List<Long> dataIdList = new ArrayList<>();
        HashMap<String, Object> param = new HashMap<>();
        param.put(StringConstant.CORPID,corpid);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("focus",BasicConstant.ONE);
        param.put("start", BasicConstant.ZERO);
        param.put("pageNum", 1000);
        param.put("orderByStr","customer_id");
        if (!isShare) {
            param.put("userId",userId);
        }
        List<CustomerFocusEntity> entitys = customerFocusModel.findEntitys(param);
        if (CollectionsUtil.isNotEmpty(entitys)) {
            entitys.forEach(item -> {dataIdList.add(item.getCustomerId());});
        }
        if (CollectionsUtil.isEmpty(dataIdList)) {
            coolAppHomeMenuVO.setCustomerList(new ArrayList<>());
            return coolAppHomeMenuVO;
        }

        // 查询阶段推进器
        HashMap<String, Object> map = new HashMap<>();
        map.put(StringConstant.CORPID,corpid);
        map.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        map.put("isNow",BasicConstant.ONE);
        map.put("dataIdIn",dataIdList);
        map.put("orderByStr","into_time desc");
        map.put("start", BasicConstant.ZERO);
        map.put("pageNum", BasicConstant.FIVE);
        //查出最新更新过阶段推进器的5个dataId
        List<CustomerStageLogEntity> stageLogEntityList = customerStageLogModel.findEntitys(map);
        dataIdList.clear();
        for (CustomerStageLogEntity stageLogEntity : stageLogEntityList) {
            dataIdList.add(stageLogEntity.getDataId());
        }
        StageGetDTO stageGetDTO = new StageGetDTO();
        stageGetDTO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());

        // 5个重点客户
        List<CustomerInfoVO> customerList = new ArrayList<>();
        List<CustomerEntityExt> entityExtList = customerModel.getByKeys(dataIdList, corpid);
        for (CustomerEntityExt entity : entityExtList) {
            JSONObject data = entity.getData();
            if (data == null) {
                continue;
            }
            CustomerInfoVO customerInfoVO = new CustomerInfoVO();
            customerInfoVO.setId(entity.getDataId());
            customerInfoVO.setName(data.getString(CustomerManagementEnum.NAME.getAttr()));
            customerInfoVO.setAppId(entity.getAppId());
            customerInfoVO.setMenuId(entity.getMenuId());
            customerInfoVO.setFormId(entity.getFormId());
            customerList.add(customerInfoVO);
        }
        coolAppHomeMenuVO.setCustomerList(customerList);
        // 只有客户的阶段，这里可以先写死
        coolAppHomeMenuVO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        coolAppHomeMenuVO.setSubBusinessType(XbbRefTypeEnum.CUSTOMER_FOCUS.getCode());
        coolAppHomeMenuVO.setSaasMark(SaasMarkEnum.SAAS.getCode());
        coolAppHomeMenuVO.setDistributorMark(DistributorMarkEnum.OTHER.getCode());

        return coolAppHomeMenuVO;
    }

    /***
     * 酷应用首页业务菜单
     *
     * @param
     * @throws
     * @return List<String>
     * @author hongxiao
     * @date 2022-09-02 19:17
     */
    private List<String> getBusinessAlias() {
        return Arrays.asList(XbbRefTypeEnum.CUSTOMER.getAlias(), XbbRefTypeEnum.ALL_OPPORTUNITY.getAlias(),
                XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getAlias(), XbbRefTypeEnum.CONTRACT.getAlias(),
                XbbRefTypeEnum.COMMUNICATE_PLAN.getAlias(), XbbRefTypeEnum.SIGNIN.getAlias(),
                XbbRefTypeEnum.WORK_REPORT.getAlias());
    }
}
